//
//  LoginManager.m
//  dataGathering
//
//  Created by macmini on 15/1/29.
//  Copyright (c) 2015年 shuili. All rights reserved.
//

#import "LoginManager.h"
#import "LatestLayerListModel.h"
#import "LatestLayerModelManager.h"
#import "FMDB.h"

@implementation LoginManager

+(LoginResult)loginUsingUsername:(NSString*)name andPassword:(NSString*)pwd
{
    __block LoginResult result = LoginResultServerError;
    NSDictionary *parameters = @{@"username": name,@"password":pwd};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //申明返回的结果是json类型
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //申明请求的数据是json类型
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    //发送请求
    [manager POST:URL_LOGIN parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
        
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",resultDic);
        //CFBooleanRef* success = [resultDic objectForKey:@"success"];
        NSNumber *number = [resultDic objectForKey:@"success"];
        
        if([number boolValue]){
            
            result = LoginResultSuccess;
            int err;
            sqlite3 *db;
            FMDatabase *fmdb;
            NSString *appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            NSString* dbpath = [appDocumentPath stringByAppendingPathComponent:@"workset.sqlite"];
            
            err = sqlite3_open_v2([dbpath UTF8String], &db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, NULL);
            sqlite3_enable_load_extension(db, 1);
            
            fmdb = [FMDatabase databaseWithPath:dbpath];
            [fmdb setDB:db :dbpath];
            
            FMResultSet *rsCheckUserInfoQuery= [fmdb executeQuery:@"select count(*) from sqlite_master where type = 'table' and name='user_info_table'"];
            if([rsCheckUserInfoQuery next]){
                int n = [rsCheckUserInfoQuery intForColumnIndex:0];
                if(n == 0){
                    [fmdb executeUpdate:DATABASECMD_USERINFOTABLE_CREATE];
                }
                [rsCheckUserInfoQuery close];
            }
            
            [fmdb executeUpdate:@"INSERT OR REPLACE INTO user_info_table(name, pwd, realname, department) VALUES (?,?,?,?)",(NSString*)[(NSDictionary*)[resultDic objectForKey:@"result"] objectForKey:@"username"],pwd,(NSString*)[(NSDictionary*)[resultDic objectForKey:@"result"] objectForKey:@"realname"],(NSString*)[(NSDictionary*)[resultDic objectForKey:@"result"] objectForKey:@"department"]];
        
            [[NSUserDefaults standardUserDefaults] setObject:[(NSDictionary*)[resultDic objectForKey:@"result"] objectForKey:@"username"] forKey:@"username"];
            [[NSUserDefaults standardUserDefaults] setObject:[(NSDictionary*)[resultDic objectForKey:@"result"] objectForKey:@"realname"] forKey:@"realname"];
            [[NSUserDefaults standardUserDefaults] setObject:[(NSDictionary*)[resultDic objectForKey:@"result"] objectForKey:@"department"] forKey:@"department"];
            
            
            NSDictionary *getLayerListparameters = @{@"username": name};
            
            AFHTTPRequestOperationManager *layerListRequestManager = [AFHTTPRequestOperationManager manager];
            layerListRequestManager.responseSerializer = [AFJSONResponseSerializer serializer];
            layerListRequestManager.requestSerializer=[AFJSONRequestSerializer serializer];
            
            [layerListRequestManager POST:URL_GETLAYERLIST parameters:getLayerListparameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSString *requestTmp = [NSString stringWithString:operation.responseString];
                NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
                NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
                
                NSNumber *getLayernumber = [resultDic objectForKey:@"success"];
                
                if([getLayernumber boolValue]){
                    NSDictionary *layerListDict = [resultDic objectForKey:@"result"];
                    NSError *error;
                    LatestLayerListModel *latestLayerListModel = [[LatestLayerListModel alloc] initWithDictionary:layerListDict error:&error];
                    NSLog(@"json parse error is %@",error);
                    
                    [[LatestLayerModelManager sharedInstance] setLatestLayerModel:latestLayerListModel];
                    
                    //[self downloadIcons:latestLayerListModel];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [SVProgressHUD dismiss];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"loginFinished" object:[NSNumber numberWithInteger:LoginResultSuccess]];
                    });
                    
                }
                
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
                [[NSNotificationCenter defaultCenter] postNotificationName:@"loginFinished" object:[NSNumber numberWithInteger:LoginResultSuccess]];
            }];

            
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            result = LoginResultWrongInfo;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"loginFinished" object:[NSNumber numberWithInteger:result]];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        result = LoginResultServerError;
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        [[NSNotificationCenter defaultCenter] postNotificationName:@"loginFinished" object:[NSNumber numberWithInteger:result]];
    }];
    return result;
    
}

+(void)downloadIcons:(LatestLayerListModel*)model
{
    NSMutableArray *operationArray = [[NSMutableArray alloc] initWithCapacity:10];
    for(GroupModel *gModel in [[model feature] groups])
    {
        if(![self checkIfIconFileExist:[gModel icon]])
        {
            NSString *iconDownloadURL = ROOT_URL@"icon/";
            
            AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[iconDownloadURL stringByAppendingString:[gModel icon]]]]];
            [operationArray addObject:operation];
            
        }
        for(LayerModel *lModel in [gModel layers])
        {
            if(![self checkIfIconFileExist:[lModel icon]])
            {
                NSString *iconDownloadURL = ROOT_URL@"icon/";
                
                AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[iconDownloadURL stringByAppendingString:[lModel icon]]]]];
                [operationArray addObject:operation];
                
            }
        }
    }
    if([operationArray count] == 0)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"loginFinished" object:[NSNumber numberWithInteger:LoginResultSuccess]];
        });
    } else {
        NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:operationArray progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
            
        } completionBlock:^(NSArray *operations) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"loginFinished" object:[NSNumber numberWithInteger:LoginResultSuccess]];
            });
        }];
        
        [[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];
    }
}

+(BOOL)checkIfIconFileExist:(NSString*)fileName
{
    NSFileManager* fm=[NSFileManager defaultManager];
    NSString *appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [appDocumentPath stringByAppendingString:@"/LayerIcons"];
    
    if (![fm fileExistsAtPath:filePath]) {
        NSLog(@"there is no Directory: %@",filePath);
        [fm createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
        return NO;
    }
    filePath = [filePath stringByAppendingString:@"/"];
    filePath = [filePath stringByAppendingString:fileName];
    if([fm fileExistsAtPath:filePath])
    {
        return YES;
    } else {
        return NO;
    }
}

@end
